﻿ /*************************************************************************
File:   as/publish.as
Author: Duykham
UpDate: 11/09/2006
TODO:   Using for publishCam.FLA
/*************************************************************************/
trace ("#included: publish.as");
///////////////////////////////////////////////////////////////////////////
//TODO: included files
///////////////////////////////////////////////////////////////////////////
//TODO: khai bao bien
// Create the Microphone and Camera objects.
//var cameras_cb:mx.controls.ComboBox;
var user_mic = Microphone.get ();
var thisCamId = _root.camNumber;
var user_cam = Camera.get (thisCamId);
// Create the NetConnection object.
var publish_nc = new NetConnection ();
// Create listener objects to be used with the components.
var connectListener = new Object ();
var rsoMessages;
// Variable to store the RSO.
var rsoCameras;
// Variable to store the RSO.
var stream_ns;
// NetStream for streaming.
var record_ns;
// NetStream for recording.
var send_ns;
// NetStream for sending data.
var nameOfCam = _root.camName;
var displayName = _root.disName;
var myMotionLevel = _root.userMotionLevel;
trace ("myMotionLevel: " + myMotionLevel);
//Khoi tao bien thuoc component ProgressBar
var motion_pb : mx.controls.ProgressBar;
motion_pb.mode = "manual";
motion_pb.label = "Motion level %3%%";
var Active;
//trang thai hoat dong cua Cam, bien duoc truyen qua sendData
var len;
var oldDate;
//co hieu de clearInterval ham khoi dong ShareObject
var flag = false;
var flag2 = false;

//MotionLevel cao nhat cua Camera
var maxMotionLevel = 0;
//DOING
//on Jan 18 2007
//var startHour = _root.CFG.alarmStartTime.substr(0,2);
var startHour = _root.CFG.alarmStartTime.substr(0,2);
trace ("startHour: "+startHour);
var startMinute = _root.CFG.alarmStartTime.substr(3,2);
trace ("startMinute: "+startMinute);

//trace ("_root.CFG.alarmStartTime: "+_root.CFG.alarmStartTime);
//trace ("_root.CFG.fmsApp: "+_root.CFG.fmsApp);
//var text1_txt = _root.CFG.alarmStartTime;
var text1_txt = startHour+" : "+startMinute;
///////////////////////////////////////////////////////////////////////////
//TODO: Initialize
preview_btn.enabled = false;
camID_txt._visible = false;
cam_txt._visible = false;
motion_txt._visible = false;
priority_txt._visible = false;
display_txt._visible = false;
status_mc.onRollOver = function ()
{
	toolTip.show (title_txt, 90, 24, 125, 127);
};
status_mc.onRollOut = function ()
{
	toolTip.hide ();
};
// Initialize the microphone threshold and camera mode and quality.
//Mic
user_mic.setSilenceLevel (10, 2000);
//Camera
user_cam.setMode (320, 240, 5);
user_cam.setMotionLevel (50, 2000);
user_cam.setQuality (0, 100);
user_cam.setLoopback (true);
// Set the loopback to true so user can see what the output stream looks like.
// Connect to the FlashMediaServer application.
publish_nc.connect (_root.CFG.fmsApp);
send_ns = new NetStream (publish_nc);
send_ns.publish ("sendData_" + displayName);
// Define the listener for the Publish button.
connectListener.click = function (event)
{
	// The Record toggle button has a selected value of true or false.
	// Neu dung, bat dau phat hinh chuyen dong
	if (event.target.selected)
	{
		user_cam.setMotionLevel (myMotionLevel, 2000);
		event.target.label = "Pause";
		title_txt = "Connected...";
		status_mc.gotoAndStop (1);
		toolTip.show (title_txt, 90, 24, 125, 127);
		exit_mc._visible = false;
		preview_btn.enabled = true;
		// Display the video in the Video object.
		//on 20060921
		record_vid.attachVideo (user_cam);
		// Create the NetStream object, and add the audio and video.
		stream_ns = new NetStream (publish_nc);
		stream_ns.attachAudio (user_mic);
		stream_ns.attachVideo (user_cam);
		// Publish the stream.
		stream_ns.publish (displayName);
		//////////UpLoad thong so cac Cameras////////////////
		rsoCameras = SharedObject.getRemote ("cams", publish_nc.uri, true);
		rsoCameras.connect (publish_nc);
		/////////// Ghi lai ngay gio phat hinh vao log//////////////
		rsoMessages = SharedObject.getRemote ("log/" + clock.strDate, publish_nc.uri, true);
		rsoMessages.connect (publish_nc);
		// Chen them mot cam vao file .fso
		addNewCam (displayName);
	} 
	else
	{
		event.target.label = "Continue";
		title_txt = "Disconnected";
		status_mc.gotoAndStop (3);
		toolTip.show (title_txt, 90, 24, 125, 127);
		// Clear the video and audio from the Video and NetStream objects.
		record_vid.attachVideo (null);
		//record_vid.clear ();
		stream_ns.attachAudio (null);
		stream_ns.attachVideo (null);
		// Stop publishing and close the stream.
		stream_ns.publish (false);
		stream_ns.close ();
		rsoMessages.connect (false);
		//removeCam (cam_txt.text);
		removeCam (displayName);
		//rsoCameras.connect (false);
		_root.maxMotionLevel = 0;
	}
};

//TODO: Khi phat hien chuyen dong
user_cam.onActivity = function (isActive : Boolean)
{
	var themeColor : String = (isActive) ? "haloGreen" : "haloOrange";
	motion_pb.setStyle ("themeColor", themeColor);
	if (thisCamId==_root.CFG.rfidCam)//Neu day chinh la RFID Camera
	{
		_root.io=(isActive)?0:1;
	}
	if (isActive && title_txt == "Connected...")
	{
		//OUT
		/*if (thisCamId==_root.CFG.rfidCam)//Neu day chinh la RFID Camera
		{
			_root.io=0;
		}*/
		
		if (clock.strDate != undefined && user_cam.activityLevel < 100)
		{
			if (clock.alarmFlg)
			{
			Active = 1;
			callVB (nameOfCam, user_cam.activityLevel);
			//Edit on 20060930 - them vao user_activityLevel
			title_txt = "Motion detected";
			status_mc.gotoAndStop (2);
			toolTip.show (title_txt, 90, 24, 125, 127);
			_root.preview_vid.attachVideo (null);
			_root.preview_vid.attachVideo (user_cam);
			record_ns = new NetStream (publish_nc);
			record_ns.attachAudio (user_mic);
			record_ns.attachVideo (user_cam);
			record_ns.publish ("archive/" + clock.strDate + "/" + displayName, "append");
			if (rsoMessages.data.logs == undefined)
			{
				rsoMessages.data.logs = new Array ();
			}
			if (clock.strTime != undefined && user_cam.activityLevel < 100)
			{
				rsoMessages.data.logs.push ( 
				{
					label : clock.strTime + " [" + displayName + "]", data : "(" + user_cam.activityLevel + "%)"
				});
			}
			}
		}
	} 
	else
	{
		//IN
		/*if (thisCamId==_root.CFG.rfidCam)//Neu day chinh la RFID Camera
		{
			_root.io=1;
		}*/
		
		Active = 0;
		record_ns.attachVideo (null);
		record_ns.attachAudio (null);
		// Stop publishing and close the stream.
		record_ns.publish (false);
		record_ns.close ();
		if (title_txt != "Disconnected")
		{
			title_txt = "Connected...";
			toolTip.show (title_txt, 90, 24, 125, 127);
			status_mc.gotoAndStop (1);
		}
	}
};
pblsh_btn.toggle = true;
pblsh_btn.addEventListener ("click", connectListener);
pblsh_btn.label = "Please wait...";
title_txt = "Stopped";
//TODO: add a new cam
addNewCam = function (camStr : String)
{
	trace ("addNewCam = function (camStr : String)");
	var camName = camStr;
	trace ("camName: " + camName);
	var flag : Boolean = false;
	trace (flag);
	if (rsoCameras.data.cams == undefined)
	{
		trace ("if (rsoCameras.data.cams == undefined)");
		rsoCameras.data.cams = new Array ();
		rsoCameras.data.cams.push ( 
		{
			label : camName, data : camName
		});
	} 
	else
	{
		var camArr = rsoCameras.data.cams;
		for (var i : Number = 0; i < camArr.length; i ++)
		{
			//kiem tra xem ten Camera da ton tai hay chua?
			if (camName == camArr [i].label)
			{
				//bat co hieu
				flag = true;
			}
		}
		if (flag == false)
		{
			rsoCameras.data.cams.push ( 
			{
				label : camName, data : camName
			});
			trace ("chen them mot camera: " + camName);
		}
	}
};
//TODO: remove cam
removeCam = function (camStr : String)
{
	var camName = camStr;
	var camArr = rsoCameras.data.cams;
	for (var i : Number = 0; i < camArr.length; i ++)
	{
		if (camName == camArr [i].label)
		{
			camArr.splice (i, 1);
			// loai bo Cam danh sach
			
		}
	}
};
//
this.onEnterFrame = function ()
{
	if (clock.strDate != undefined && flag == false && rsoCameras.data.cams != undefined)
	{
		clearInterval (intervalID);
		//addNewCam ("NoCameras");
		flag = true;
		flag2= true;
		//if (rsoCameras.data.cams == undefined)
		//{
			//trace ("if (rsoCameras.data.cams == undefined)");
			//rsoCameras.data.cams = new Array ();
		//}
		//pblsh_btn.onRelease ();
	}
	if (flag2){
		pblsh_btn.onRelease ();
		flag2 = false;
	}
	
	if (this.title_txt != "Disconnected")
	{
		motion_pb.setProgress (user_cam.activityLevel, 100);
		//send_ns = new NetStream (publish_nc);
		//tao mot NetStream moi dung de truyen bien den client
		//send_ns.publish ("sendData_" + displayName);
		//trace("displayName: "+displayName);
		//bien duoc truyen qua goi sendData
		send_ns.send ("activeLevel", user_cam.activityLevel);//truyen activityLevel cua cam
		if(clock.alarmFlg)
		{
			send_ns.send ("onActive", Active);//truyen trang thai cua cam
		
		//lien tuc gui bien MotionLevel cao nhat cho VB
		if (user_cam.activityLevel > _root.maxMotionLevel)
		{
			_root.maxMotionLevel = user_cam.activityLevel;
			callVB (nameOfCam, _root.maxMotionLevel);
		}
		}
		if (oldDate != clock.strDate)
		//khi chuyen ngay se goi ham restart
		//de khoi dong lai ket noi
		{
			restart ();
		}
	}
};
/*
//on exit
exit_mc.onRelease = function ()
//this.close = function ()
{
	stream_ns.close ();
	send_ns.close ();
	publish_nc.close ();
	gotoAndPlay ("step1");
};
*/
callVB = function (camName : String, motionlevel : String)
{
	trace ("camName: " + camName);
	trace ("motionlevel: " + motionlevel )
	FSCommand (camName, motionlevel);
	//Edit on 20060930 - them vao motion level
	//truyen CamName cho VB
	
};
//Khoi dong ShareObject
initialSO = function ()
{
	intervalID = setInterval (function ()
	{
		//////////UpLoad thong so cac Cameras////////////////
		rsoCameras = SharedObject.getRemote ("cams", publish_nc.uri, true);
		rsoCameras.connect (publish_nc);
		/////////// Ghi lai ngay gio phat hinh vao log//////////////
		rsoMessages = SharedObject.getRemote ("log/" + clock.strDate, publish_nc.uri, true);
		rsoMessages.connect (publish_nc);
		//////////////////////////////////
		if (rsoCameras.data.cams == undefined)
		{
			rsoCameras.data.cams = new Array ();
		}
	}, 100);
};

//Khoi dong lai ket noi
//Edit on 05/01/2007
//khoi tao lai cac ket noi cho CAM va LOG
//cac luong khac: VIDEO va SENDDATA van giu nguyen
restart = function ()
{
	if (this.title_txt != "Disconnected")
	{
		//////////UpLoad thong so cac Cameras////////////////
		rsoCameras = SharedObject.getRemote ("cams", publish_nc.uri, true);
		rsoCameras.connect (publish_nc);
		/////////// Ghi lai ngay gio phat hinh vao log//////////////
		rsoMessages = SharedObject.getRemote ("log/" + clock.strDate, publish_nc.uri, true);
		rsoMessages.connect (publish_nc);
		//////////////////////////////////
	}
	oldDate = clock.strDate;
};

//Delay 
//05/11/2006:--> co the ham nay chua hoat dong that su chinh xac --> can kiem tra lai
function delay(numb:Number)
{
	var time1 = (new Date( )).getTime( );
	var time2 = time1;
	var bool:Boolean = false;
	do {
		time2 = (new Date( )).getTime( );
	}
	while
	(time2 <= time1 + numb);
	bool = true;
}
initialSO ();
//oldDate = clock.strDate;
//pblsh_btn.onRelease ();
